package com.daekwang.util;

import java.io.IOException;
import java.util.Properties;

public class Property
{
	private volatile static Property	instance; //volatile 을 사용하지 않으면 변수의 원자성이 보장되지 않는다.
	private ClassLoader					classLoader;

	public static Property getInstance()
	{
		/*
		 * instance가 null 일때만 동기화를 걸어줌
		 * 그럼으로서 처음에 한번만 동기화됨
		 */
		if (instance == null)
		{
			synchronized (Property.class)
			{
				if (instance == null)
				{
					instance = new Property();
				}
			}
		}

		return instance;
	}

	private Property()
	{
		classLoader = getClass().getClassLoader();
	}

	public String getString(String key)
	{
		try
		{
			Properties prop = getResource("mr.properties");
			String value = prop.getProperty(key);
			return value;
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public int getInt(String key, int defaultValue)
	{
		String value = getString(key);
		if (value != null)
		{
			try
			{
				return Integer.parseInt(value);
			}
			catch (Exception e)
			{
				return defaultValue;
			}
		}

		return -1;
	}

	public String getMessage(String key)
	{
		try
		{
			Properties prop = getResource("message.properties");
			String value = prop.getProperty(key);
			return value;
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	private Properties getResource(String resource) throws IOException
	{

		Properties prop = new Properties();

		prop.load(classLoader.getResourceAsStream(resource));

		return prop;
	}
}
